package com.easychat.controller;

import com.easychat.common.LeaseException;
import com.easychat.common.Result;
import com.easychat.dto.MessageSendDto;
import com.easychat.dto.TokenUserInfoDto;
import com.easychat.entity.ChatMessage;
import com.easychat.entity.LoginUser;
import com.easychat.entity.config.AppConfig;
import com.easychat.entity.constants.Constants;
import com.easychat.enums.ExceptionCodeEnum;
import com.easychat.enums.MessageTypeEnum;
import com.easychat.service.ChatMessageService;
import com.easychat.service.ChatSessionUserService;
import com.easychat.utils.LoginUserHolder;
import com.easychat.utils.StringTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * @author 10 2024/10/22
 */
@RestController
@RequestMapping("/chat")
@Slf4j
public class ChatController{

    @Resource
    private ChatMessageService chatMessageService;
    @Resource
    private ChatSessionUserService chatSessionUserService;
    @Resource
    private AppConfig appConfig;

    @GetMapping("/sendMessage")
    public Result sendMessage(@NotEmpty String contactId, //Urobot 机器人
                              @NotEmpty @Max(500) String messageContent,
                              @NotNull Integer messageType, //2 普通聊天信息
                              Long fileSize,
                              String fileName,
                              Integer fileType){
        TokenUserInfoDto tokenUserInfoDto = LoginUserHolder.get();
//        tokenUserInfoDto = new TokenUserInfoDto(); 测试ai使用
//        tokenUserInfoDto.setUserId("Urobot1");
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setContactId(contactId);
        chatMessage.setMessageContent(messageContent);
        chatMessage.setFileName(fileName);
        chatMessage.setFileType(fileType);
        chatMessage.setMessageType(messageType);
        MessageSendDto messageSendDto = chatMessageService.saveMessage(chatMessage,tokenUserInfoDto);
        log.info("发送消息成功:{}",messageSendDto);
        return Result.ok(messageSendDto);


    }


    @PostMapping("/uploadFile")
     public Result uploadFile(@NotNull Long messageId,
                              @NotNull MultipartFile file,
                              @NotNull MultipartFile cover){

        TokenUserInfoDto tokenUserInfoDto = LoginUserHolder.get();
        chatMessageService.saveMessageFile(tokenUserInfoDto.getUserId(),messageId,file,cover);
        return Result.ok();
    }
    @GetMapping("/downloadFile")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response,@NotEmpty String fileId,
                               @NotNull Boolean showover){
        TokenUserInfoDto tokenUserInfoDto = LoginUserHolder.get();
        OutputStream out = null;
        FileInputStream in = null;
        try {
            File file = null;
            if(!StringTools.isNumber(fileId)){
                String avatarFolderName = Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_AVATAR_NAME;
                String avatarPath = appConfig.getProjectFolder() + avatarFolderName + fileId + Constants.IMAGE_SUFFIX;
                if(showover){
                    avatarPath = avatarPath + Constants.COVER_IMAGE_SUFFIX;
                }
                file = new File(avatarPath);
                if(!file.exists()){
                    throw new LeaseException(ExceptionCodeEnum.IMAGE_NOT_EXIST);
                }else {
                    file = chatMessageService.downloadFile(tokenUserInfoDto,Long.parseLong(fileId),showover);
                }
                response.setContentType("application/x-msdownload;charset=UTF-8");
                response.setHeader("Content-Disposition","attachment;");
                response.setContentLengthLong(file.length());

                in = new FileInputStream(file);
                byte[] byteData = new byte[1024];
                //通过流返回
                out = response.getOutputStream();
                int len;
                while ((len = in.read(byteData))!=-1){
                    out.write(byteData,0,len);
                }
                out.flush();
            }
        }catch (Exception e){
            log.error("下载文件失败",e);
        }finally {
            if(out!=null){
                try {
                    out.close();
                }catch (Exception e){
                    log.error("IO异常",e);
                }
            }
            if(in!=null){
                try {
                    in.close();
                }catch (Exception e){
                    log.error("IO异常",e);
                }
            }
        }
    }

}
